package yxy.game.pm2.command.friend;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.friend.FriendModule;

/** 好友 申请加好友 */
@MessageType(proto = Command.FriendApplicant, classtype = FriendMessage.FriendApplicantRequest.class)
public class CMD_FriendApplicant extends Command<FriendMessage.FriendApplicantRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendApplicantRequest request) {
		String applyCode = messageSource.getTag();
		String playerCode = request.getPlayerCode();

		FriendMessage.FriendApplicantResponse.Builder response = FriendMessage.FriendApplicantResponse.newBuilder();

		if (applyCode.equals(playerCode)) {
			send(messageSource, response, Result.FriendCantAddSelf);
			return;
		}

		FriendModule friendModule = FriendModule.get(playerCode);
		FriendModule applyModule = FriendModule.get(applyCode);
		try {
			if (friendModule.tryLock() && applyModule.tryLock()) {
				if (friendModule.vacant() <= 0) {
					// 玩家满了就不再接受申请
					send(messageSource, response, Result.Success);
					return;
				}
				if (friendModule.getBlack().contains(applyCode)) {
					// 申请者在对方黑名单里
					send(messageSource, response, Result.Success);
					return;
				}
				if (applyModule.getBlack().contains(playerCode)) {
					// 对方在申请者黑名单里
					send(messageSource, response, Result.FriendCantAddBlack);// 黑名单玩家不能添加为好友
					return;
				}

				friendModule.getApply().add(applyCode);
				friendModule.set();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			friendModule.unlock();
			applyModule.unlock();
		}
	}

	private void send(MessageSource messageSource, FriendMessage.FriendApplicantResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}